#!/bin/bash
# Print running container names for Armbian MOTD (Docker).
# Standalone: discovers containers itself and prints a formatted line,
# identical to the original header behavior.

set -o pipefail

safe_source() { [[ -f "$1" ]] && . "$1"; }

THIS_SCRIPT="containers-info"
MOTD_DISABLE=""

# Optional overrides
safe_source /etc/default/armbian-motd
for f in ${MOTD_DISABLE}; do
	[[ "${f}" == "${THIS_SCRIPT}" ]] && exit 0
done

_motd_spacer() {
  local tag="${1:-after-header}"
  local dir="/run/armbian-motd"; local stamp="$dir/.${tag}.printed"
  mkdir -p "$dir" 2>/dev/null
  [[ -e "$stamp" ]] || { echo ""; : > "$stamp"; }
}

# one-time spacer after header (marks that something printed before Performance)
_motd_mark_after_header() {
  local base="/run/armbian-motd"
  mkdir -p "$base" 2>/dev/null || base="${XDG_RUNTIME_DIR:-/tmp}/armbian-motd"
  mkdir -p "$base" 2>/dev/null || return 0
  local stamp="${base}/.after_header.printed"
  [[ -e "$stamp" ]] || { echo ""; : >"$stamp"; }
}


list_docker_names() {
  # Only show names if Docker is active and CLI is present
  if systemctl is-active --quiet docker && command -v docker >/dev/null 2>&1; then
    docker ps --format '{{.Names}}' 2>/dev/null | paste -sd', ' -
  fi
}

main() {
  local names
  names="$(list_docker_names)"
  if [[ -n "$names" ]]; then
    _motd_mark_after_header
    printf ' Containers:   \x1B[92m%s\x1B[0m\n' "$names"
  fi
}

# If sourced, don't run main; if executed, run.
(return 0 2>/dev/null) || { main; exit 0; }
